import axios from 'axios';
import { defineStore, storeToRefs } from 'pinia';

import { usePermissionStore } from '@/store';
import type { UserInfo } from '@/types/interface';

const InitUserInfo: UserInfo = {
  name: '', // 用户名，用于展示在页面右上角头像处
  roles: [], // 前端权限模型使用 如果使用请配置modules/permission-fe.ts使用
  number: '', // 用户帐号
  userId: 0, // 用户id
  isAdmin: false, // 是否为管理员
};

export const useUserStore = defineStore('user', {
  state: () => ({
    token: 'main_token', // 初始 token 为空
    userInfo: { ...InitUserInfo },
  }),
  getters: {
    // roles: (state: { token: string; userinfo: UserInfo }) => {
    //   return state.userinfo.roles;
    // },
    // isAdmin: (state: { token: string; userinfo: UserInfo }) => {
    //   return state.userinfo.isAdmin;
    // },
    roles: (state) => state.userInfo.roles,
    isAdmin: (state) => state.userInfo.isAdmin,
    getUserInfo: (state) => state.userInfo,
  },
  actions: {
    async login(userInfo: { number: string; password: string }) {
      try {
        this.logout();
        const response = await axios.post('/api/user/login', userInfo);
        if (response.status === 200 && response.data.success === true) {
          console.info(response);
          this.token = '1103';
          this.userInfo = response.data.data;
          // 根据 isAdmin 设置角色
          if (this.userInfo.isAdmin) {
            this.userInfo.roles = ['all'];
          } else {
            this.userInfo.roles = ['user'];
          }
          const permissionStore = usePermissionStore();
          if (this.userInfo.isAdmin) {
            permissionStore.initRoutes(['all']);
          } else {
            permissionStore.initRoutes(['user']); // test all so set up all should user
          }
        } else {
          throw new Error(response.data.message || '登录失败');
        }
      } catch (e) {
        console.error('登录失败:', e);
        throw e;
      }
    },
    async logout() {
      try {
        await axios.delete('/api/user/logout');
        this.token = '';
        this.userInfo = { ...InitUserInfo };
      } catch (e) {
        console.error('注销失败:', e);
      }
    },
  },
  persist: {
    afterRestore: (ctx) => {
      console.info(ctx);
      const { userInfo } = storeToRefs(ctx.store); // 使用 storeToRefs 访问 getter
      const permissionStore = usePermissionStore();
      // console.info(userInfo.value.data.isAdmin);
      // permissionStore.initRoutes(['user']); // test all so set up all should user
      if (userInfo.value.isAdmin) {
        permissionStore.initRoutes(['all']);
      } else {
        permissionStore.initRoutes(['user']); // test all so set up all should user
      }
    },
  },
});
